/*
 * libMat.c
 *
 *  Created on: 18/04/2012
 *      Author: utnso
 */

#include "libMat.h"

uint64_t potencia(uint64_t base, uint64_t potencia){
	uint64_t res;
	if(potencia == 0) res = 1;
	else for(res = base; potencia > 1; res *= base, potencia--);
	return res;
}

void intAChar(char** buffer, int32_t numero, uint8_t base){
	char* bufferAux = (char*) malloc(25);
	memset(bufferAux, '\0', 25);
	uint8_t desplazamiento = 0;
	uint8_t pot = 24;
	if(numero == 0){
		bufferAux[0] = '0';
	}else{
		if(numero < 0){
			bufferAux[0] = '-';
			desplazamiento++;
			pot--;
		}
		for(;pot >= 0 && div(numero, potencia(10, pot)).quot == 0;pot--);
		for(;desplazamiento < 25 && pot >= 0; desplazamiento++, desplazamiento++, pot--){
			bufferAux[desplazamiento] = div(numero, potencia(10, pot)).quot + 48;
		}
		if(desplazamiento == 25){
			strcpy(bufferAux, "0");
		}else{
			bufferAux[desplazamiento] = '\0';
		}
	}

	*buffer = (char*) malloc(strlen(bufferAux) + 1);
	memset(*buffer, '\0', strlen(bufferAux) + 1);
	strcpy(*buffer, bufferAux);
	free(bufferAux);
}

uint8_t esPotencia(uint64_t potencia, uint8_t base){
	if(potencia == base){
		return 1;
	} else if(potencia == 0){
		return 0;
	} else if(div(potencia,base).rem != 0){
		return 0;
	} else{
		return esPotencia(div(potencia, base).quot, base);
	}
}


uint64_t potenciaDe2Proxima(uint32_t val){
	uint32_t i = 0;
	while(val > potencia(2,i)){
		i++;
	}
	return (potencia(2,i));
}
